import { aesEncrypt, aesDecrypt } from '@/utils/crypto'

export function getLocalStorage(name, parse = false){
  const storage = localStorage.getItem(name);
  return parse ? JSON.parse(storage) : storage;
}

export function setLocalStorage(name, obj, parse = false){
  const storage = parse ? JSON.stringify(obj) : obj;
  localStorage.setItem(name, obj);
}

export function removeLocalStorage(...name){
  name.forEach(n =>{
    localStorage.removeItem(n);
  })
}

export function clearLocalStorage(){
  localStorage.clear();
}

export function getSessionStorage(name, parse = false){
  const storage = sessionStorage.getItem(name);
  return parse ? JSON.parse(storage) : storage;
}

export function setSessionStorage(name, obj, parse = false){
  const storage = parse ? JSON.stringify(obj) : obj;
  sessionStorage.setItem(name, obj);
}

export function removeSessionStorage(...name){
  name.forEach(n =>{
    sessionStorage.removeItem(n);
  })
}

export function clearSessionStorage(){
  sessionStorage.clear();
}

//设置有效期的localStorage
export function setCacheStorage(name, cache, expireTime, unit = 'second'){
  const unitMap = {
    //小时
    hour: 60*60*1000,
    //分钟
    minute: 60*1000,
    //秒
    second: 1000,
    //毫秒
    millisecond: 1
  }
  unit = unitMap.hasOwnProperty(unit) ? unit : 'second';
  const obj = {
    createTime: new Date().getTime(),
    expireTime: expireTime * (unitMap[unit] || 1000),
    cache
  }
  const cacheStr = aesEncrypt(JSON.stringify(obj))
  localStorage.setItem(name, cacheStr);
}

export function getCacheStorage(name){
  const cacheStr = aesDecrypt(getLocalStorage(name));
  const obj = JSON.parse(cacheStr);
  if(!obj){
    return obj;
  }
  const { createTime, expireTime, cache } = obj;
  if(createTime + expireTime > new Date().getTime()){
    return cache;
  }else{
    localStorage.removeItem(name);
    return null;
  }
}

export function removeCacheStorage(...name){
  removeLocalStorage(name);
}
